package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Component
@Slf4j
public class CacheClient {
    @Resource
    private StringRedisTemplate stringRedisTemplate;



    public  void set(String key, Object  value, Long  time, TimeUnit unit)
    {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr( value), time, unit);
    }
    public  void setWithLogicalExpire(String key,Object  value, Long  time, TimeUnit unit)
    {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(time));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr( redisData));
    }
    public <R,ID>  R queryWithPassThrough(String keyPrefix, ID id, Class<R> type , Function<ID,R> dbFallback, Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        //1.从redis中查询商铺缓存
        String Json = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if(StrUtil.isNotBlank(Json))
        {
            //3.存在，则返回
            return JSONUtil.toBean(Json, type);

        }
        if(Json != null)
        {
            return null;
        }
        //4.不存在，则查询数据库
        R r  = dbFallback.apply(id);
        //5.数据库不存在，返回错误
        if(r == null) {
            stringRedisTemplate.opsForValue().set(key, "",CACHE_NULL_TTL ,TimeUnit.MINUTES);
            return null;
        }
        //6.存在,则写入redis
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(r),time, unit);
        //返回
        return r;
    }


    private  static  final ExecutorService CATCH_REBUDID_EXECUTOR = Executors.newFixedThreadPool(10);
    public <R ,ID> R queryWithLogicalExpire(String keyPrefix,ID id, Class<R> type, Function<ID,R> dbFallback,Long time, TimeUnit unit) {
        String key = keyPrefix+ id;
        //1.从redis中查询商铺缓存
        String Json = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if(StrUtil.isBlank(Json))
        {

            return null;
        }
        //4.命中，需要先把json反序列化为对象
        RedisData rd = JSONUtil.toBean(Json, RedisData.class);
        JSONObject data = (JSONObject) rd.getData();
        R r = JSONUtil.toBean(data, type);
        //5.判断是否过期
        if(rd.getExpireTime().isAfter(LocalDateTime.now()))
        {
            //5.2 未过期，直接返回
            return r;
        }

        //6.缓存重建
        //6.1 获取互斥锁
        String lock = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lock);
        //6.2 判断是否获取成功
        if(isLock)
        {
            //6.2.1 成功，开启独立线程，实现缓存重建
            CATCH_REBUDID_EXECUTOR.submit(()->{
                try {
                    R r1= dbFallback.apply(id);
                    setWithLogicalExpire(key, r1, time, unit);
                }catch (Exception e)
                {
                    throw new RuntimeException(e);
                }
                finally {
                    unLock(lock);
                }

            });
        }

        //6.3 失败，返回错误
        //6.4 成功，返回数据
        //7.返回
        return r;
    }

//    public <R,ID> saveShop2Redis(String keyPrefix,ID id,Long expireSeconds, Function<ID,R> dbFallback) throws InterruptedException {
//        //1.查询店铺数据
//        R r= dbFallback.apply(id);
//        Thread.sleep(200);
//        //2.封装逻辑过期时间
//        RedisData redisData = new RedisData();
//        redisData.setData(r);
//        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
//        //3.写入redis
//        stringRedisTemplate.opsForValue().set(keyPrefix + id, JSONUtil.toJsonStr(redisData));
//    }




    public  boolean tryLock(String key)
    {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    public void unLock(String key)
    {
        stringRedisTemplate.delete(key);
    }


}
